package cn.myspringboot.system.service.impl;

import cn.myspringboot.base.service.impl.BaseServiceImpl;
import cn.myspringboot.system.mapper.MenuMapper;
import cn.myspringboot.system.service.MenuService;
import cn.myspringboot.user.domain.Menu;
import cn.myspringboot.user.query.MenuQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public PageInfo<Menu> queryPage(MenuQuery query) {
        PageHelper.startPage(query.getPage(),query.getSize());
        List<Menu> menus = menuMapper.queryPage(query);
        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        return pageInfo;
    }

    @Override
    public List<Menu> getByNameTree() {
        List<Menu> all = menuMapper.getAll();
        List<Menu> menuList = getTree(all);
        return menuList;
    }
    public static List<Menu> getTree(List<Menu> all) {
        if (all != null && !all.isEmpty()) {
            // 获取 id 将 id 设为 key，menu 设为值
            Map<Long, Menu> map = all.stream()
                    .filter(menu -> menu.getId() != null) // 过滤掉 id 为 null 的菜单
                    .collect(Collectors.toMap(Menu::getId, menu -> menu, (existing, replacement) -> existing));
            List<Menu> menuList = new ArrayList<>();
            for (Menu menu : all) {
                if (menu.getParentId() == null) {
                    menuList.add(menu);
                } else {
                    Menu parentMenu = map.get(menu.getParentId());
                    parentMenu.getChildren().add(menu);
                }
            }
            return menuList;
        } else {
            return null;
        }
    }
}
